package com.skyworth.web.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.resourceresolver.SpringResourceResourceResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class ThymeleafConfig {

    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(webTemplateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        return viewResolver;
    }

    @Bean
    public SpringTemplateEngine webTemplateEngine() {
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();

        springTemplateEngine.setTemplateResolver(webTemplateResolver());

        Set<IDialect> additionalDialects = new HashSet<IDialect>();
        additionalDialects.add(new LayoutDialect());
        additionalDialects.add(new ShiroDialect());
        springTemplateEngine.setAdditionalDialects(additionalDialects);

        return springTemplateEngine;
    }

    @Bean
    public TemplateResolver webTemplateResolver() {
        TemplateResolver templateResolver = baseHtmlTemplateResolver();
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }

    private TemplateResolver baseHtmlTemplateResolver() {
        TemplateResolver templateResolver = new TemplateResolver();
        templateResolver.setResourceResolver(springResourceResourceResolver());
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("LEGACYHTML5");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);
        return templateResolver;
    }

    @Bean
    public SpringResourceResourceResolver springResourceResourceResolver() {
        return new SpringResourceResourceResolver();
    }
}